import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom'
import { connect } from 'dva';
import {
  Form, Input, DatePicker, Select, Button, Card, Upload, Radio, Modal, Tooltip,Icon,message,Row,Col
} from 'antd';
import {Map} from 'react-bmap'  ;
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';
import UploadFile from '../../components/Upload/index';

const FormItem = Form.Item;
const { TextArea } = Input;
const Option = Select.Option;

@connect(state => ({
  seekHelp: state.seekHelp,
}))
@Form.create()
export default class SeekAdd extends PureComponent {
  state = {
    id:-1,
    rsId:1,
    userId:1,

    areaTitle:'走失位置',
    areaAddr:'',
    photoLabel:'人物近照',
    lng: 87.490354,
    lat: 43.853289,

    maxFileSize:3,
    fileList: [],
    photoInfo:[],

    Bmap:'',

    showDetail:false,

    seekTypeValue:"1",
  };

  ////初始化渲染后触发 整个过程只调用一次
  componentDidMount() {
    const { form , dispatch} = this.props;
    this.initBmap();

    if(this.props.location.query) {
      var seekHelpId = this.props.location.query.seekHelpId;
      var showDetail = this.props.location.query.showDetail;
      if (seekHelpId) {
        if(showDetail){
          this.setState({
            showDetail:showDetail
          });
        }
        const params = {
          seekHelpId: seekHelpId
        };

        dispatch({
          type: 'seekHelp/fetchGetSeekHelpInfoById',  //请求的action
          payload: params,
          callback: (res) => {
            form.setFields({
              seekerName: {value: res.seekerName},
              seekTitle: {value: res.seekTitle},
              seekDes: {value: res.seekDes},
              contacts: {value: res.contacts},
              contactsTell: {value: res.contactsTell}
            })
            var arr = JSON.parse(res.photoInfo);

            for(var i in arr){
              this.state.fileList.push({
                uid: (-99+i),
                name: 'default'+i+'.png',
                status: 'done',
                url: arr[i]
              })
            }
            console.log(res.seekType);
            this.setState({
              photoInfo: arr,
              fileList:this.state.fileList,
              lng:res.lng,
              lat:res.lat,
              areaAddr:res.areaAddr,
              id:res.id,
              rsId:res.rsId,
              seekTypeValue:res.seekType+"",
            });
          }
        });
      }
    }
  }

  initBmap(){
    const map = new BMap.Map("seekHelpAddress");

    function G(id) {
      return document.getElementById(id);
    }

    map.enableScrollWheelZoom(true);
    var point = new BMap.Point(this.state.lng,this.state.lat);
    map.centerAndZoom(point, 15);
    map.addEventListener("click", this.dragendStop);

    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
      {"input" : "suggestId"
        ,"location" : map
      }
    );
    ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
      var str = "";
      var _value = e.fromitem.value;
      var value = "";
      if (e.fromitem.index > -1) {
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
      }
      str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

      value = "";
      if (e.toitem.index > -1) {
        _value = e.toitem.value;
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
      }
      str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
      G("searchResultPanel").innerHTML = str;
    });

    var myValue;
    ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
      var _value = e.item.value;
      myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
      G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
      setPlace();
    });

    function setPlace(){
      map.clearOverlays();    //清除地图上所有覆盖物
      function myFun(){
        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
        map.centerAndZoom(pp, 18);
        map.addOverlay(new BMap.Marker(pp));    //添加标注
      }
      var local = new BMap.LocalSearch(map, { //智能搜索
        onSearchComplete: myFun
      });
      local.search(myValue);
    }

    var geolocation = new BMap.Geolocation();
    // 开启SDK辅助定位
    geolocation.enableSDKLocation();
    geolocation.getCurrentPosition(function(r){
      if(this.getStatus() == BMAP_STATUS_SUCCESS){
        var mk = new BMap.Marker(r.point);
        map.addOverlay(mk);
        map.panTo(r.point);
      }
      else {
        alert('定位失败');
      }
    });

    this.setState({
      Bmap: map
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {

        values.userId = this.state.userId;
        values.rsId = this.state.rsId;
        values.photoInfo = JSON.stringify(this.state.photoInfo);
        if(this.state.id != -1) values.id = this.state.id;

        values.addrCoordinate='{lng:'+this.state.lng+",lat:"+this.state.lat+"}";
        values.addrStr='';
        var tel = values.contactsTell;

        if(!(/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/.test(tel))){
          message.error("不是完整的11位手机号或者正确的手机号前七位");
          return false;
        }

       this.props.dispatch({
          type: 'seekHelp/fetchSubmitSeekHelp',
          payload: values,
          callback:(res) =>{
            message.success(res.msg);
            setTimeout(this.cancelBack(),200);
          }
        });
      }
    });
  }

  getImageSrc = (imgSrc) => {
    this.setState({
      photoInfo: imgSrc
    });
  }

  handleRadioChange = ( e ) => {

    var _pl = '', _al = '';
    switch (e.target.value){
      case '1':
        _pl = '走失位置';
        _al = '人物近照';
        break;
      case '2':
        _pl = '丢失位置';
        _al = '物品照片';
        break;
      case '3':
        _pl = '车辆位置';
        _al = '车辆照片';
        break;
      case '4':
        _pl = '拾到位置';
        _al = '物品照片';
        break;
      case '5':
        _pl = '位置';
        _al = '照片';
        break;
    }
    this.setState({
      areaTitle: _al,
      photoLabel: _pl
    });
  }


  cancelBack = () => {
    history.go(-1);
  }

  //地图拖动停止事件
  dragendStop = ({type, target, pixel, point}) => {
    const { Bmap } = this.state;
    this.setState({
      lat: point.lat,
      lng: point.lng
    });

    Bmap.clearOverlays();
    var mk = new BMap.Marker(point);
    Bmap.addOverlay(mk);
    Bmap.panTo(point);
  }

  render() {
    const { formLoading } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const {  fileList ,areaAddr,areaTitle,photoLabel,maxFileSize,showDetail,seekTypeValue} = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    /*const prefixSelector = getFieldDecorator('prefix', {
      initialValue: '86',
      })(
        <Select style={{ width: 70 }}>
          <Option value="86">+86</Option>
          <Option value="87">+87</Option>
        </Select>
      );*/

    return (
      <PageHeaderLayout >
        <Card bordered={false}>
          <Form
            onSubmit={this.handleSubmit}
            hideRequiredMark
            style={{ marginTop: 8 }}
          >
           {/* 求助类型  1 寻人 2 寻物  3 车辆求助  4 寻找失主    5 其他*/}
            <FormItem
              {...formItemLayout}
              label="类型"
            >
              {getFieldDecorator('seekType', {
                initialValue: seekTypeValue,
              })(
                <Radio.Group onChange={this.handleRadioChange} disabled={showDetail} >
                  <Radio value="1">寻人</Radio>
                  <Radio value="2">寻物</Radio>
                  <Radio value="3">车辆求助</Radio>
                  <Radio value="4">寻找失主</Radio>
                  <Radio value="5">其他求助</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="求助人"
            >
              {getFieldDecorator('seekerName', {
                rules: [{
                  required: true, message: '请输入求助人',
                }],
              })(
                <Input placeholder="请输入求助人"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="标题"
            >
              {getFieldDecorator('seekTitle', {
                rules: [{
                  required: true, message: '请输入求助人',
                }],
              })(
                <Input placeholder="请输入求助人"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="描述"
            >
              {getFieldDecorator('seekDes', {
                rules: [{
                  required: true, message: '请输入请求描述',
                }],
              })(
                <TextArea style={{ minHeight: 32 }} placeholder="走失时间、走失地点、人物状况、外貌特征" rows={4}  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="联系人"
            >
              {getFieldDecorator('contacts', {
                rules: [{
                  required: true, message: '请输入联系人',
                }],
              })(
                <Input placeholder="请输入联系人"  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="联系电话"
            >
              {getFieldDecorator('contactsTell', {
                rules: [{
                  required: true, message: '请输入电话',
                }],
              })(
                <Input placeholder="请输入电话"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label='搜地点'
              style={{marginBottom:2}}
            >
              <div id="r-result"><Input placeholder="搜地点" id="suggestId"  disabled={showDetail}  /></div>
              <div id="searchResultPanel" style={{border:'1px solid #C0C0C0',width:'100%',height:'auto', display:'none'}}></div>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={areaTitle}
              style={{marginBottom:2}}
            >
              <div id="seekHelpAddress" style={{width:'100%',height:400}}></div>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={photoLabel}
            >
              <UploadFile
                maxFileCount = {maxFileSize}
                defaultList={fileList}
                getImgSrc={(imgSrc)=> this.getImageSrc(imgSrc)}
                buttonName = "照片上传"
                acceptName = 'image/*'
                suffixDefault = {['jpg']}
                data={{
                userId:1,
                filePath:'test/photo/'}}
              />
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}  help="导播提交后，信息将推送到主持人界面，只有主持人播报并一键推送后才会在APP中显示" >
              <Button type="primary" htmlType="submit" loading={formLoading}  disabled={showDetail} >
                提交求助信息
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={() => this.cancelBack()}>取消</Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
